import { GeoJSON } from "ol/format";
import { $httpGeo } from '@/api/index'
import ImageLayer from 'ol/layer/Image';
import ImageCanvasSource from 'ol/source/ImageCanvas';

export const drawKriging = async (map) => {
    let { value, x, y } = getPoint(map)

    let kriging = require('./kriging')
    let variogram = kriging.train(value, x, y, 'gaussian', 0, 100)

    let res = require('./xm_border_datav.json')
    let xm_feature = new GeoJSON({ geometryName: 'geom', }).readFeatures(res);

    let polygon = xm_feature[0].getGeometry()
    let extent = polygon.getExtent()
    let width = (extent[2] - extent[0]) / 200

    let coord = polygon.getCoordinates()

    let grid = kriging.grid(coord[1], variogram, width)
    let layer = imageLayer(kriging, grid)
    map.addLayer(layer)
}

const getPoint = (map) => {
    let allLayer = map.getAllLayers()
    let value = []
    let x = []
    let y = []
    let features = allLayer[5].getSource().getFeatures()
    features.forEach((v, i) => {
        let lonlat = v.getGeometry().getCoordinates()
        value.push(Math.ceil(Math.random() * 100))
        x.push(lonlat[0])
        y.push(lonlat[1])
    })
    return { value, x, y }
}

const imageLayer = (kriging, grid) => {
    let color = ["#3ea4c2", "#95c1c3", "#c2d7ae", "#e9ee9b", "#fbe77f", "#fdb269", "#ffb56a", "#f88959", "#f04a4d"]
    let layer = new ImageLayer({
        source: new ImageCanvasSource({
            canvasFunction: (extent, resolution, pixelRatio, size, projection) => {
                let canvas = document.createElement('canvas');
                canvas.width = size[0];
                canvas.height = size[1];
                canvas.style.display = 'block';
                canvas.getContext('2d').globalAlpha = 0.7;
                kriging.plot(canvas, grid, [extent[0], extent[2]], [extent[1], extent[3]], color);
                return canvas;
            }
        }),
        visible: false
    })
    return layer
}